package org.jflame.context.spring.jackson;

import org.jflame.commons.util.DateHelper;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Objects;

import org.springframework.context.i18n.LocaleContextHolder;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;

public class LocalDateTimeWithContextZoneDeserializer extends LocalDateTimeDeserializer {

    private static final long serialVersionUID = 8710902004243612082L;

    public LocalDateTimeWithContextZoneDeserializer() {
        super(DateHelper.FORMATTER_YYYY_MM_DD_HH_mm_ss);
    }

    public LocalDateTimeWithContextZoneDeserializer(DateTimeFormatter dtf) {
        super(dtf);
    }

    @Override
    public LocalDateTime deserialize(JsonParser parser, DeserializationContext context) throws IOException {
        LocalDateTime date = super.deserialize(parser, context);

        ZoneId contextZoneId = LocaleContextHolder.getTimeZone()
                .toZoneId();
        ZoneId jacksonZone = context.getTimeZone()
                .toZoneId();
        if (contextZoneId != null && !Objects.equals(contextZoneId, jacksonZone)) {
            return DateHelper.changeZone(date, contextZoneId, jacksonZone);
        }
        return date;
    }
}
